package com.chenxinzhimusic.page

import android.os.Build
import androidx.annotation.RequiresApi
import androidx.compose.foundation.background
import androidx.compose.foundation.basicMarquee
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Popup
import coil3.compose.AsyncImage
import com.chenxinzhimusic.R
import com.chenxinzhimusic.api.Api
import com.chenxinzhimusic.data.loveKey
import com.chenxinzhimusic.data.playListKey
import com.chenxinzhimusic.refreshFlow
import com.chenxinzhimusic.sharedFlow
import com.chenxinzhimusic.util.startDownloadService
import com.chenxinzhimusic.viewmodel.Abslist
import com.chenxinzhimusic.viewmodel.MusicInfo
import com.chenxinzhimusic.viewmodel.PlayList
import com.chenxinzhimusic.viewmodel.addMusic
import com.chenxinzhimusic.viewmodel.addToLove
import com.chenxinzhimusic.viewmodel.removeMusic
import com.chenxinzhimusic.viewmodel.toMusicInfo
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.launch

@RequiresApi(Build.VERSION_CODES.TIRAMISU)
@Composable
fun MusicItemView(
    music: Abslist,
    sharedFlow: MutableSharedFlow<Unit>,
    index: Int,
    rememberLazyListState: LazyListState
) {
    val coroutineScope = rememberCoroutineScope()
    var showPopup by rememberSaveable { mutableStateOf(false) }
    var pressOffset by rememberSaveable { mutableLongStateOf(Offset.Zero.packedValue) }
    var isUp by rememberSaveable { mutableStateOf(false) }
    val density = LocalDensity.current

    val artworkUri = if (music.webAlbumpicShort.isBlank()) {
        "https://img1.kuwo.cn/star/starheads/${music.webArtistpicShort}"
    } else {
        "https://img2.kuwo.cn/star/albumcover/${music.webAlbumpicShort}"
    }
    var content = LocalContext.current
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .combinedClickable(onLongClick = {
                isUp =
                    index + 4 > rememberLazyListState.layoutInfo.visibleItemsInfo.last().index
                showPopup = true
            }) {
                coroutineScope.launch {
                    sharedFlow.emit(Unit)
                    val musicInfo = MusicInfo(
                        music.dCTARGETID,
                        music.nAME,
                        music.aRTIST,
                        artworkUri.replace("/120/", "/1000/"),
                        music.dURATION.toInt(),
                        0,
                        "",
                        music.aLBUM
                    )
                    content.addMusic(
                        musicInfo
                    )
                    refreshFlow.tryEmit(Unit)
                }
            }
            .pointerInput(Unit) {
                awaitEachGesture {
                    val awaitPointerEvent = awaitPointerEvent()
                    val offset = awaitPointerEvent.changes[0].position
                    pressOffset = Offset(
                        x = offset.x,
                        y = offset.y
                    ).packedValue
                }
            }
            .padding(horizontal = 10.dp)
    ) {
        Column(horizontalAlignment = Alignment.CenterHorizontally) {
            Spacer(modifier = Modifier.height(5.dp))
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween,
                modifier = Modifier
                    .padding(vertical = 6.dp)
                    .fillMaxWidth()
            ) {
                AsyncImage(
                    model = artworkUri,
                    contentDescription = "图片",
                    contentScale = ContentScale.Crop,
                    error = painterResource(R.drawable.ic_launcher_foreground),
                    modifier = Modifier
                        .size(60.dp)
                        .clip(RoundedCornerShape(8.dp))
                )
                Spacer(modifier = Modifier.width(8.dp))

                Column(modifier = Modifier.weight(7f)) {
                    Text(
                        text = music.nAME,
                        style = MaterialTheme.typography.titleMedium,
                        maxLines = 1,
                        modifier = Modifier.basicMarquee(),
                        color = Color.White
                    )
                    Text(
                        text = "${music.aRTIST} - ${music.aLBUM}",
                        style = MaterialTheme.typography.bodyMedium,
                        color = Color.Gray,
                        modifier = Modifier.basicMarquee(),
                        maxLines = 1,
                    )
                }

                Spacer(modifier = Modifier.width(8.dp))
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.weight(1f)
                ) {
                    val duration = music.dURATION.toInt()
                    Text(
                        text = String.format("%02d:%02d", duration / 60, duration % 60),
                        style = MaterialTheme.typography.bodySmall,
                        modifier = Modifier.basicMarquee(),
                        color = Color.Gray
                    )
                }
            }
            Spacer(modifier = Modifier.height(5.dp))
        }


        // 弹出菜单
        if (showPopup) {
            Popup(
                offset = with(density) {
                    Offset(pressOffset).let {
                        IntOffset(
                            it.x.toInt(),
                            if (isUp) it.y.toInt() - (200.dp.toPx()
                                .toInt()) else it.y.toInt()
                        )
                    }

                },
                onDismissRequest = { showPopup = false }
            ) {
                Column(
                    modifier = Modifier
                        .clip(RoundedCornerShape(10.dp))
                        .background(Color.Black.copy(alpha = 0.8f))
                        .width(200.dp)
                        .padding(vertical = 8.dp)
                ) {
                    listOf(
                        "收藏到我喜欢" to {
                            content.apply {
                                coroutineScope.launch {
                                    addToLove(music.toMusicInfo())
                                    refreshFlow.emit(Unit)
                                }
                            }
                        },
                        "下载" to {
                            content.apply {
                                coroutineScope.launch {
                                    var toMusicInfo = music.toMusicInfo()
                                    toMusicInfo.musicId.let {
                                        Api.getMusicUrl(it)?.data?.url?.let {
                                            startDownloadService(
                                                it,
                                                "${toMusicInfo.title} - ${toMusicInfo.artist}"
                                            )
                                        }
                                    }
                                }
                            }
                        }
                    ).forEach { item ->
                        Text(
                            text = item.first,
                            modifier = Modifier
                                .fillMaxWidth()
                                .clickable {
                                    showPopup = false
                                    item.second()
                                }
                                .padding(12.dp),
                            color = Color.White
                        )
                    }
                }
            }
        }
    }
}

@RequiresApi(Build.VERSION_CODES.TIRAMISU)
@Composable
fun MusicItemView(
    music: MusicInfo,
    playList: PlayList,
    index: Int,
    showLove: Boolean = false,
    rememberLazyListState: LazyListState,
    modifier: Modifier = Modifier,
    shadowSetting: @Composable Modifier.() -> Modifier = { this },
    dragButton: @Composable () -> Unit = {}
) {
    val coroutineScope = rememberCoroutineScope()
    var showPopup by rememberSaveable { mutableStateOf(false) }
    var pressOffset by rememberSaveable { mutableLongStateOf(Offset.Zero.packedValue) }
    var isUp by rememberSaveable { mutableStateOf(false) }
    val density = LocalDensity.current
    val content = LocalContext.current
    val artworkUri = music.picUrl
    Box(
        modifier = modifier
            .fillMaxWidth()
            .combinedClickable(onLongClick = {
                isUp =
                    index + 4 > rememberLazyListState.layoutInfo.visibleItemsInfo.last().index && playList.musicList.size > 4
                showPopup = true
            }) {
                coroutineScope.launch {
                    sharedFlow.emit(Unit)
                    val musicInfo = MusicInfo(
                        music.musicId,
                        music.title,
                        music.artist,
                        music.picUrl,
                        music.duration,
                        0,
                        "",
                        music.album
                    )
                    content.addMusic(
                        musicInfo, playList
                    )
                    refreshFlow.tryEmit(Unit)


                }
            }
            .pointerInput(Unit) {
                awaitEachGesture {
                    val awaitPointerEvent = awaitPointerEvent()
                    val offset = awaitPointerEvent.changes[0].position
                    pressOffset = Offset(
                        x = offset.x,
                        y = offset.y
                    ).packedValue
                }
            }
            .padding(horizontal = 10.dp)
            .composed {
                shadowSetting()
            }
    ) {
        Column(horizontalAlignment = Alignment.CenterHorizontally) {
            Spacer(modifier = Modifier.height(5.dp))
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween,
                modifier = Modifier
                    .padding(vertical = 6.dp)
                    .fillMaxWidth()
            ) {
                AsyncImage(
                    model = artworkUri,
                    contentDescription = "图片",
                    contentScale = ContentScale.Crop,
                    error = painterResource(R.drawable.ic_launcher_foreground),
                    modifier = Modifier
                        .size(60.dp)
                        .clip(RoundedCornerShape(8.dp))
                )
                Spacer(modifier = Modifier.width(8.dp))

                Column(modifier = Modifier.weight(7f)) {
                    Text(
                        text = music.title,
                        style = MaterialTheme.typography.titleMedium,
                        maxLines = 1,
                        modifier = Modifier.basicMarquee(),
                        color = Color.White
                    )
                    Text(
                        text = "${music.artist} - ${music.album}",
                        style = MaterialTheme.typography.bodyMedium,
                        color = Color.Gray,
                        modifier = Modifier.basicMarquee(),
                        maxLines = 1,
                    )
                }

                Spacer(modifier = Modifier.width(8.dp))
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.weight(3f)
                ) {
                    val duration = music.duration.toInt()
                    Text(
                        text = String.format("%02d:%02d", duration / 60, duration % 60),
                        style = MaterialTheme.typography.bodySmall,
                        modifier = Modifier.basicMarquee(),
                        color = Color.Gray
                    )
                    dragButton()
                }
            }
            Spacer(modifier = Modifier.height(5.dp))
        }

    }
    // 弹出菜单
    if (showPopup) {
        Popup(
            offset = with(density) {
                Offset(pressOffset).let {
                    IntOffset(
                        it.x.toInt(),
                        if (isUp) it.y.toInt() - (200.dp.toPx()
                            .toInt()) else it.y.toInt()
                    )
                }

            },
            onDismissRequest = { showPopup = false }
        ) {

            Column(
                modifier = Modifier
                    .clip(RoundedCornerShape(10.dp))
                    .background(Color.Black.copy(alpha = 0.8f))
                    .width(200.dp)
                    .padding(vertical = 8.dp)
            ) {
                mutableListOf(
                    "删除" to {
                        content.apply {
                            coroutineScope.launch {
                                if (showLove) {
                                    removeMusic(playListKey, music.musicId)
                                } else {
                                    removeMusic(loveKey, music.musicId)

                                }
                            }
                        }
                    },
                    "下载" to {
                        content.apply {
                            coroutineScope.launch {
                                music.musicId.let {
                                    Api.getMusicUrl(it)?.data?.url?.let {
                                        startDownloadService(
                                            it,
                                            "${music.title} - ${music.artist}"
                                        )
                                    }
                                }
                            }
                        }
                    }
                ).apply {
                    if (showLove) {
                        add("收藏到我喜欢" to {
                            content.apply {
                                coroutineScope.launch {
                                    addToLove(music)
                                    refreshFlow.emit(Unit)
                                }
                            }
                        })
                    }
                }.forEach { item ->
                    Text(
                        text = item.first,
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable {
                                showPopup = false
                                item.second()

                            }
                            .padding(12.dp),
                        color = Color.White
                    )
                }
            }
        }
    }
}


